import { history } from 'umi';
import { fakeAccountLogin, logout } from '@/services/login';
import undefined from '@/e2e/__mocks__/antd-pro-merge-less';
import { message } from 'antd';

const Model = {
  namespace: 'login',
  state: {},
  effects: {
    *login({ payload }, { call, put }) {
      // 发送请求执行登录
      const response = yield call(fakeAccountLogin, payload);

      // 判断是否登录成功
      if (response.status === undefined) {
        message.success('登录成功');
        yield put({
          type: 'changeLoginStatus',
          payload: response,
        }); // Login successfully

        // 跳转到首页
        history.replace('/');
      }
    },
    // 退出登录
    *logout(_, { call }) {
      // loading
      const load = message.loading('退出中...');

      // 请求Api 退出登录
      const response = yield call(logout);

      // 判断是否退出成功
      if (response.status === undefined) {
        // 删除本地存储的token 和 userInfo
        localStorage.removeItem('access_token');
        localStorage.removeItem('userInfo');

        message.success('退出成功');
        // 重定向
        history.replace('/login');
      }
      load();
    },
  },
  reducers: {
    changeLoginStatus(state, { payload }) {
      // 将token 传入localStorage
      localStorage.setItem('access_token', payload.access_token);
      return { ...state };
    },
  },
};
export default Model;
